<template>
  <div>
    <el-upload
        :action="uploadUrl"
        :headers="uploadHeaders"
        :show-file-list="false"
        :on-success="handleUploadSuccess"
        :before-upload="beforeUpload">
      <video v-if="fileUrl" :src="fileUrl" :style="getImgStyle()" class="avatar" controls/>
      <i v-else :style="getImgUploadIconStyle()" class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: "UploadVideo",
  props: {
    fileSizeLimitM: {
      required: false,
      default: 1,
      type: Number
    },
    videoWidth: {
      required: false,
      default: 320,
      type: Number
    },
    videoHeight: {
      required: false,
      default: 180,
      type: Number
    },
  },
  data() {
    return {
      uploadUrl: "/api/file/upload/no/expire",
      uploadHeaders: {
        'Authentication': sessionStorage.getItem("token")
      },
      fileUrl: "",
    }
  },
  methods: {
    setReviewUrl(url) {
      this.fileUrl = url
    },
    getImgUploadIconStyle() {
      return {
        width: `${this.videoWidth}px`,
        height: `${this.videoHeight}px`,
        lineHeight: `${this.videoHeight}px`,
      };
    },
    getImgStyle() {
      return {
        width: `${this.videoWidth}px`,
        height: `${this.videoHeight}px`,
      };
    },
    handleUploadSuccess(res, file) {
      this.fileUrl = file.response.data.url
      this.$emit('getUploadUrl', file.response.data.url);
    },
    beforeUpload(file) {
      const limit = file.size / 1024 / 1024 < this.fileSizeLimitM;

      if (!limit) {
        this.$message.error(`上传文件大小不能超过 ${this.fileSizeLimitM}MB!`);
      }
      return limit;
    },
  }
}
</script>

<style scoped>
.avatar-uploader {
  text-align: center;
  width: 100%
}
.avatar-uploader-icon:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;

}
.avatar {
  display: block;
}
</style>
